#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
try:
    import ujson as json
except:
    import json
from controls import mongo
from controls import data_topic_title_mysql
from controls import data_topic_gallery_mysql
from controls import data_topic_note_mysql
from controls import data_topic_note_img_mysql
from controls import data_manage_user_mysql
from controls import data_user_feed_mysql
from controls import data_user_brief_mysql
from controls import data_topic_note_like_mysql
from controls import data_img_base_mysql
from utils.file_util import file_upload, img_file_upload, get_100_size_imglink
from utils import log
from config import etc

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("username")

class TopicNoteHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return
        return self.render('cms/topic_note.html')

class TopicNoteDelHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return

    def post(self):
        try:
            noteid = self.get_argument('noteid')

            if not noteid:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            note = data_topic_note_mysql.get_topic_note_by_noteid(noteid)
            if not note:
                res = {'ret': 1, 'msg': 'get note error'}
                self.write(json.dumps(res))
                self.finish()
                return

            userid = note['userid']

            if not data_user_feed_mysql.del_user_feed({
                'userid': userid,
                'optype': data_user_feed_mysql.USER_FEED_TYPE_NOTE_POST,
                'targetid': noteid,
            }):
                res = {'ret': 1, 'msg': 'delete manage feed error'}
                self.write(json.dumps(res))
                self.finish()
                return

            if not data_topic_note_img_mysql\
                    .delete_topic_note_img_by_noteid(noteid):
                res = {'ret': 1, 'msg': 'delete img error'}
                self.write(json.dumps(res))
                self.finish()
                return

            if not data_topic_note_mysql\
                    .delete_topic_note_by_noteid(noteid):
                res = {'ret': 1, 'msg': 'delete note error'}
                self.write(json.dumps(res))
                self.finish()
                return

            res = {'ret': 0, 'msg': 'success'}
            self.write(json.dumps(res))
            self.finish()
            return

        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return

class TopicNotePostHandler(BaseHandler):
    def post(self, *args, **kwargs):
        userid = self.get_argument('userid')
        topicid = self.get_argument('topicid')
        note = self.get_argument('note')
        tags = self.get_argument('tags')
        place = self.get_argument('place')

        if not topicid:
            log.w('params fetching error')
            res = {'ret': 1, 'msg': '参数获取错误'}
            self.write(json.dumps(res))
            self.finish()
            return

        try:
            imgid_list = []

            if not (note or self.request.files):
                log.i('add note img error')
                self._generate_res(1, "请添加note或图片")
                return

            for i in xrange(len(self.request.files)):
                tmp_file = self.request.files[("file[%s]" % i)][0]
                file_res = img_file_upload(tmp_file)

                if file_res and file_res['ret'] == 0:
                    imgid_list.append(str(file_res['res']['imgid']))

            noteid = mongo.count_noteid()

            new_note_item = {
                'topicid': topicid,
                'noteid': noteid,
                'note': note,
                'complete': 0,
                'userid': userid,
                'tags': tags,
                'place': place
            }

            if not data_topic_note_mysql\
                    .add_topic_note_item(new_note_item):
                log.i('add note img error')
                self._generate_res(1, "添加note失败")
                return

            if not data_user_feed_mysql.add_user_feed_item({
                'userid': userid,
                'optype': data_user_feed_mysql.USER_FEED_TYPE_NOTE_POST,
                'targetid': noteid,
            }):
                self._generate_res(1, '收藏失败', 'add_note_post_feed')
                return

            new_img_item = {
                'topicid': topicid,
                'noteid': noteid,
                'imgid': imgid_list,
            }
            if not data_topic_note_img_mysql\
                    .add_topic_note_img_item(new_img_item):
                log.i('add note img error')
                self._generate_res(1, "添加图片失败")
                return

            log.i('pulish note success')
            self._generate_res(0, "发布成功")
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'note_post')
            return

class UpdateTopicNoteHandler(BaseHandler):
    def get(self, *args, **kwargs):
        noteid = self.get_argument('noteid')

        if not noteid:
            log.w('params fetching error')
            res = {'ret': 1, 'msg': '参数获取错误'}
            self.write(json.dumps(res))
            self.finish()
            return

        note_item = data_topic_note_mysql.get_topic_note_by_noteid(noteid)

        if not note_item:
            log.w('noteid error')
            res = {'ret': 1, 'msg': 'noteid error'}
            self.write(json.dumps(res))
            self.finish()
            return

        note_img = data_topic_note_img_mysql.get_topic_note_img_by_noteid(noteid)
        note_imgid_list = note_img['imgid']

        note_img_map = data_img_base_mysql\
            .get_img_url_by_imgid_list(note_imgid_list)

        note_item['imgs'] = []
        note_item['thumbs'] = []
        for i in note_imgid_list:
            if i in note_img_map.keys():
                note_item['imgs'].append(note_img_map[i])
                note_item['thumbs'].append(get_100_size_imglink(note_img_map[i]))

        user_brief = data_user_brief_mysql\
            .get_user_brief_by_userid(note_item['userid'])

        note_item['user'] = user_brief
        note_item['user']['thumblink'] =\
            note_item['user']['imglink'][0:len(note_item['user']['imglink'])-1]\
            + '132'

        like_count = data_topic_note_like_mysql\
            .get_note_like_count_by_noteid(noteid)
        note_item['like_count'] = like_count

        res = {'ret': 0, 'msg': '获取成功', 'res': note_item}
        self.write(json.dumps(res))
        self.finish()
        return

    def post(self, *args, **kwargs):
        userid = self.get_argument('userid')
        topicid = self.get_argument('topicid')
        note = self.get_argument('note')
        tags = self.get_argument('tags')
        place = self.get_argument('place')

        if not (userid and topicid):
            log.w('params fetching error')
            res = {'ret': 1, 'msg': '参数获取错误'}
            self.write(json.dumps(res))
            self.finish()
            return

        try:
            imgid_list = []

            if not (note or self.request.files):
                log.i('add note img error')
                self._generate_res(1, "请添加note或图片")
                return

            for i in xrange(len(self.request.files)):
                tmp_file = self.request.files[("file[%s]" % i)][0]
                file_res = img_file_upload(tmp_file)

                if file_res and file_res['ret'] == 0:
                    imgid_list.append(str(file_res['res']['imgid']))

            noteid = mongo.count_noteid()

            note_item = {
                'topicid': topicid,
                'noteid': noteid,
                'note': note,
                'complete': 0,
                'userid': userid,
                'tags': tags,
                'place': place
            }

            if not data_topic_note_mysql\
                    .update_topic_note_by_noteid(noteid, note_item):
                log.i('add note error')
                self._generate_res(1, "添加note失败")
                return

            img_item = {
                'topicid': topicid,
                'noteid': noteid,
                'imgid': imgid_list,
            }
            if not data_topic_note_img_mysql\
                    .update_topic_note_img_by_noteid(img_item):
                log.i('add note img error')
                self._generate_res(1, "添加图片失败")
                return

            log.i('pulish note success')
            self._generate_res(0, "发布成功")
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'note_post')
            return